package com.qf.base.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author 30909
 */
public class Base64Util {

    /**
     * 图片转base64
     * Java原生类中使用 BufferedImages 来表达一个图片
     *
     * @param image 带转化的图片
     * @return 返回的Base64 编码
     */
    public static String image2Base64(BufferedImage image) {
        String base64 = null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, "png", stream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        //内存流的数据变成字节数组
        byte[] bytes = stream.toByteArray();
        //字节数组转化为base64
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 文件换 base64
     */
    public static String image2Base64(String fileName) {
        File file = new File(fileName);
        try {
            BufferedImage read = ImageIO.read(file);
            return image2Base64(read);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * base64 转 BufferedImage
     */
    public static BufferedImage base64ToImage(String base64) {
        //健壮性校验
        if (base64 == null && base64.length() > 0) {
            return null;
        }

        byte[] bytes = Base64.decodeBase64(base64);
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        //转流图片

        try {
            return ImageIO.read(stream);

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 把一个base64数据保存为文件
     * @param base64    图片数据
     * @param fileName  文件名
     * @return          返回类型
     */
    public static File base64ToFile(String base64, String fileName) {
        if (base64 == null || base64.length() == 0) {
            return null;
        }
        byte[] bytes = Base64.decodeBase64(base64);
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return file;
    }

}
